package com.ocom.common.request.exposeapi.boczhxy;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;


public class AESService {

	private static final String CHARSET = "GBK";

	public static String encrypt(String data, String key, String vector) {
		if (data == null)
			return null;
		try {
			Cipher cipher = cipherInit(hexToBytes(key), hexToBytes(vector),
					Cipher.ENCRYPT_MODE);
			byte[] cipherBytes = cipher.doFinal(data.getBytes(CHARSET));
			return bytesToHex(cipherBytes);
		} catch (Exception var7) {
			var7.printStackTrace();
			return null;
		}
	}

	public static String decrypt(String data, String key, String vector) {
		if (data == null)
			return null;
		try {
			Cipher cipher = cipherInit(hexToBytes(key), hexToBytes(vector),
					Cipher.DECRYPT_MODE);
			byte[] plainBytes = cipher.doFinal(hexToBytes(data));
			return new String(plainBytes, CHARSET);
		} catch (Exception var7) {
			var7.printStackTrace();
			return null;
		}
	}

	private static Cipher cipherInit(byte[] key, byte[] vector, int cipherValue)
			throws Exception {
		SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
		IvParameterSpec iv = new IvParameterSpec(vector);
		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
		cipher.init(cipherValue, skeySpec, iv);
		return cipher;
	}

	public static String bytesToHex(byte[] bytes) {
		return DatatypeConverter.printHexBinary(bytes);
	}

	public static byte[] hexToBytes(String hexString) {
		return DatatypeConverter.parseHexBinary(hexString);
	}


}